package com.ethink.component.oss;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.ethink.component.oss.properties.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xin
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({OssProperties.class})
public class OssClient {

    @Autowired
    private OssProperties ossProperties;

    /**
     * oss 上传文件
     *
     * @param bucketName
     * @param inputStream
     * @param objectName
     * @return url
     */
    public Map<String,String>upload(String bucketName, InputStream inputStream, String objectName, String filePath) {
        Map<String,String> map = new HashMap<>();
       // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        //拼接
        objectName = filePath +"/" + objectName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
        String url = null;
        try {
            ossClient.putObject(bucketName, objectName, inputStream);
            url = ossClient.generatePresignedUrl(bucketName,objectName,DateUtil.date()).toString();
            url = url.substring(0,url.indexOf("?"));
            map.put("url",url);
            map.put("key",objectName);
            return map;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            return map;
        }
    }
}